package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.BotanyFileLogic;
import cn.topevery.garden.dal.logic.BotanyTreeInfoLogic;
import cn.topevery.garden.entity.impot.BotanyTreeInfoImportParam;
import cn.topevery.garden.entity.po.BotanyFile;
import cn.topevery.garden.entity.po.BotanyTreeInfo;
import cn.topevery.garden.entity.query.BotanyTreeInfoQuery;
import cn.topevery.garden.entity.vo.BotanyTreeInfoVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import cn.topevery.garden.wapi.utils.StatusUtils;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.GeometryHelper;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.enums.GeometryTypeEnum;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Geometry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 古树名木管理
 *
 * @author code -generate
 * @created 2021 -08-26 17:32:40
 * @date 2021 -08-26
 */
@Api(tags = "古树名木管理接口")
@RestController
@RequestMapping("/botanyTreeInfo")
public class BotanyTreeInfoController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    BotanyTreeInfoLogic botanyTreeInfoLogic;

    @Autowired
    BotanyFileLogic botanyFileLogic;


    /**
     * 获取分页列表
     *
     * @param query the query
     * @return json result
     * @author wenzhao.lin
     * @created 2021 -08-26 17:32:40 List page json result.
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<BotanyTreeInfo>> listPage(@RequestBody BotanyTreeInfoQuery query) {
        return JsonResult.ok(botanyTreeInfoLogic.listPage(query));
    }

    /**
     * 描述 新增/编辑 信息.
     *
     * @param dto the dto
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-26 17:32:40 Save or update json result.
     */
    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody BotanyTreeInfo dto) {
        if(dto.mapRangesPoints!=null && dto.mapRangesPoints.size()>0){
            Geometry temp = GeometryHelper.getGeometry(GeometryHelper.ListtoWellKnownText(dto.mapRangesPoints, GeometryTypeEnum.PLANE));
            dto.setGeomBd09(temp);
        }
        boolean isSave = botanyTreeInfoLogic.saveOrUpdate(getUser().id.toString(),dto);
        if(isSave){
            // 保存附件
            botanyFileLogic.saveOrUpdate(getUser().id.toString(), dto.getId(),dto.fileList,2);
        }
        return JsonResult.ok(true);
    }

    /**
     * 描述 通过id获取详情
     *
     * @param id the id
     * @return the by id
     * @author wenzhao.lin
     * @created 2021 -08-25 10:53:27
     */
    @GetMapping(value = "/getById")
    @ApiOperation(value = "通过id获取详情")
    public JsonResult<?> getById(Integer id) {
        if (id == null) {
            return JsonResult.error("id不能为空");
        }
        BotanyTreeInfo botany = botanyTreeInfoLogic.getById(id);
        if(botany.getGeomBd09()!=null) {
            botany.mapRangesPoints=GeometryHelper.getGeometryPoint(botany.getGeomBd09());
            botany.setGeomBd09(null);
        }

        List<BotanyFile> botanyFiles = botanyFileLogic.getListByPid(id, 2);
        botany.setFileList(botanyFiles);

        return JsonResult.ok(botany);
    }


    /**
     * 描述 根据自增ID批量删除.
     *
     * @param ids the ids
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-26 17:32:40 Delete batch by id json result.
     */
    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        botanyTreeInfoLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<BotanyTreeInfoVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, BotanyTreeInfoVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<BotanyTreeInfoVO> newData = new ArrayList<>();
        for (BotanyTreeInfoVO p : persons) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = botanyTreeInfoLogic.isExit("c_code", p.getCode());
            if (isExists1) {
                anaylsisRes += "树木编码与现有重复；";
            }
            /*if(StringUtils.isEmpty(p.getType())){
                anaylsisRes += "类别不能为空；";
            }*/

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody BotanyTreeInfoImportParam param) {
        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (BotanyTreeInfoVO p : param.getTableData()) {
                BotanyTreeInfo tmp = getBotany(p, param.getType());
                botanyTreeInfoLogic.saveOrUpdate(user.id.toString(),tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }

    /**
     * 描述 获取实体类.
     *
     * @param p the p
     * @return the botany
     * @author wenzhao.lin
     * @created 2021 -08-26 17:20:07 Get botany botany.
     */
    public BotanyTreeInfo getBotany(BotanyTreeInfoVO p, Integer type){
        BotanyTreeInfo tmp = new BotanyTreeInfo();

        tmp.setCode(p.getCode());
        tmp.setName(p.getName());
        tmp.setAliasName(p.getAliasName());
        tmp.setLatinName(p.getLatinName());
        tmp.setDistributionArea(p.getDistributionArea());
        tmp.setLevel(p.getLevel());
        tmp.setAddress(p.getAddress());
        tmp.setSection(p.getSection());
        tmp.setGenus(p.getGenus());
        tmp.setHight(p.getHight());
        tmp.setWeight(p.getWeight());
        tmp.setDiameter(p.getDiameter());
        tmp.setSpecial(p.getSpecial());
        tmp.setOwnership(p.getOwnership());
        tmp.setRealAge(p.getRealAge());
        tmp.setEstimateAge(p.getEstimateAge());
        tmp.setAverageRange(p.getAverageRange());
        tmp.setEastWestRange(p.getEastWestRange());
        tmp.setNorthSouthRange(p.getNorthSouthRange());
        tmp.setAltitude(p.getAltitude());
        tmp.setSlopeDirection(p.getSlopeDirection());
        tmp.setSlopeDegree(p.getSlopeDegree());
        tmp.setSlopePosition(p.getSlopePosition());
        tmp.setSoilName(p.getSoilName());
        tmp.setCompactness(p.getCompactness());
        tmp.setGrowthEnvironment(p.getGrowthEnvironment());
        tmp.setGrowthPotential(p.getGrowthPotential());
        tmp.setManageDept(p.getManageDept());
        tmp.setManageRemark(p.getManageRemark());
        tmp.setLngBd09(p.getLngBd09());
        tmp.setLatBd09(p.getLatBd09());
        if(StringUtils.isNotEmpty(p.getType())){
            tmp.setType(String.valueOf(StatusUtils.getTreeType(p.getType())));
        }else {
            tmp.setType(String.valueOf(type));
        }

        tmp.setRemark(p.getRemark());

        return tmp;
    }
}
